package com.xygj.vueblog.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 自定义登录验证过滤器
 * @author longwentao
 *
 */
public class LoginCheckPermissionFilter extends AuthorizationFilter {

    private final static Logger logger = LoggerFactory.getLogger(LoginCheckPermissionFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String url = req.getRequestURI();
        try {
            Subject subject = SecurityUtils.getSubject();

            return subject.isPermitted(url);
        } catch (Exception e) {

        }
        return false;

    }

    @Override
    /**
     * 在onAccessDenied方法中，如果用户身份为空，说明未登录，则跳转到登录页面，
     * 如果未指定跳转的路径，Shiro给了默认值的跳转页面 /login.jsp
     */
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = getSubject(request, response);
        if (subject.getPrincipal() == null) {
            saveRequestAndRedirectToLogin(request, response);
        } else {
            return true;
        }
        return false;
    }

}
